<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/dxl/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/dxl/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/dxl/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/dxl/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/dxl/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/dxl/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/dxl/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/dxl/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/dxl/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Django,">










<meta name="description" content="一 Form介绍2.1Form组件的主要功能如下:　　　　生成页面可用的HTML标签 　　　　对用户提交的数据进行校验 　　　　保留上次输入内容 2.2普通方式手写注册功能views.py 1234567891011121314# 注册def register(request):    error_msg = &quot;&quot;    if request.method == &quot;POST&quot;:        us">
<meta name="keywords" content="Django">
<meta property="og:type" content="article">
<meta property="og:title" content="Form和ModelForm">
<meta property="og:url" content="http://yoursite.com/2019/09/21/【Django】09From表单和ModelForm组件/index.html">
<meta property="og:site_name" content="我的快乐时光">
<meta property="og:description" content="一 Form介绍2.1Form组件的主要功能如下:　　　　生成页面可用的HTML标签 　　　　对用户提交的数据进行校验 　　　　保留上次输入内容 2.2普通方式手写注册功能views.py 1234567891011121314# 注册def register(request):    error_msg = &quot;&quot;    if request.method == &quot;POST&quot;:        us">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-09-21T07:27:53.977Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Form和ModelForm">
<meta name="twitter:description" content="一 Form介绍2.1Form组件的主要功能如下:　　　　生成页面可用的HTML标签 　　　　对用户提交的数据进行校验 　　　　保留上次输入内容 2.2普通方式手写注册功能views.py 1234567891011121314# 注册def register(request):    error_msg = &quot;&quot;    if request.method == &quot;POST&quot;:        us">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/dxl/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/09/21/【Django】09From表单和ModelForm组件/">





  <title>Form和ModelForm | 我的快乐时光</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/dxl/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">我的快乐时光</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/dxl/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/dxl/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/dxl/2019/09/21/【Django】09From表单和ModelForm组件/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content>
      <meta itemprop="description" content>
      <meta itemprop="image" content="/dxl/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我的快乐时光">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Form和ModelForm</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-09-21T15:24:35+08:00">
                2019-09-21
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/dxl/categories/Django/" itemprop="url" rel="index">
                    <span itemprop="name">Django</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/dxl/2019/09/21/【Django】09From表单和ModelForm组件/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/dxl/2019/09/21/【Django】09From表单和ModelForm组件/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="一-Form介绍"><a href="#一-Form介绍" class="headerlink" title="一 Form介绍"></a>一 Form介绍</h2><h3 id="2-1Form组件的主要功能如下"><a href="#2-1Form组件的主要功能如下" class="headerlink" title="2.1Form组件的主要功能如下:"></a>2.1Form组件的主要功能如下:</h3><p>　　　　生成页面可用的HTML标签</p>
<p>　　　　对用户提交的数据进行校验</p>
<p>　　　　保留上次输入内容</p>
<h3 id="2-2普通方式手写注册功能"><a href="#2-2普通方式手写注册功能" class="headerlink" title="2.2普通方式手写注册功能"></a>2.2普通方式手写注册功能</h3><p>views.py</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 注册</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">register</span><span class="params">(request)</span>:</span></span><br><span class="line">    error_msg = <span class="string">""</span></span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">"POST"</span>:</span><br><span class="line">        username = request.POST.get(<span class="string">"name"</span>)</span><br><span class="line">        pwd = request.POST.get(<span class="string">"pwd"</span>)</span><br><span class="line">        <span class="comment"># 对注册信息做校验</span></span><br><span class="line">        <span class="keyword">if</span> len(username) &lt; <span class="number">6</span>:</span><br><span class="line">            <span class="comment"># 用户长度小于6位</span></span><br><span class="line">            error_msg = <span class="string">"用户名长度不能小于6位"</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="comment"># 将用户名和密码存到数据库</span></span><br><span class="line">            <span class="keyword">return</span> HttpResponse(<span class="string">"注册成功"</span>)</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">"register.html"</span>, &#123;<span class="string">"error_msg"</span>: error_msg&#125;)</span><br></pre></td></tr></table></figure>

<p>login.html</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">    &lt;title&gt;注册页面&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">&lt;form action=<span class="string">"/reg/"</span> method=<span class="string">"post"</span>&gt;</span><br><span class="line">    &#123;% csrf_token %&#125;</span><br><span class="line">    &lt;p&gt;</span><br><span class="line">        用户名:</span><br><span class="line">        &lt;input type=<span class="string">"text"</span> name=<span class="string">"name"</span>&gt;</span><br><span class="line">    &lt;/p&gt;</span><br><span class="line">    &lt;p&gt;</span><br><span class="line">        密码：</span><br><span class="line">        &lt;input type=<span class="string">"password"</span> name=<span class="string">"pwd"</span>&gt;</span><br><span class="line">    &lt;/p&gt;</span><br><span class="line">    &lt;p&gt;</span><br><span class="line">        &lt;input type=<span class="string">"submit"</span> value=<span class="string">"注册"</span>&gt;</span><br><span class="line">        &lt;p style="color: red"&gt;&#123;&#123; error_msg &#125;&#125;&lt;/p&gt;</span><br><span class="line">    &lt;/p&gt;</span><br><span class="line">&lt;/form&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>

<h3 id="2-2使用form组件实现注册功能"><a href="#2-2使用form组件实现注册功能" class="headerlink" title="2.2使用form组件实现注册功能"></a>2.2使用form组件实现注册功能</h3><p>1、views.py</p>
<p>先定义好一个RegForm类：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django <span class="keyword">import</span> forms</span><br><span class="line"></span><br><span class="line"><span class="comment"># 按照Django form组件的要求自己写一个类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RegForm</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    name = forms.CharField(label=<span class="string">"用户名"</span>)  </span><br><span class="line">    <span class="comment">#form字段的名称写的是什么，那么前端生成input标签的时候，input标签的name属性的值就是什么</span></span><br><span class="line">    pwd = forms.CharField(label=<span class="string">"密码"</span>)</span><br></pre></td></tr></table></figure>

<p>再写一个视图函数：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 使用form组件实现注册方式</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">register2</span><span class="params">(request)</span>:</span></span><br><span class="line">    form_obj = RegForm()</span><br><span class="line">    <span class="keyword">if</span> request.method == <span class="string">"POST"</span>:</span><br><span class="line">        <span class="comment"># 实例化form对象的时候，把post提交过来的数据直接传进去</span></span><br><span class="line">        form_obj = RegForm(data=request.POST)  <span class="comment">#既然传过来的input标签的name属性值和form类对应的字段名是一样的，所以接过来后，form就取出对应的form字段名相同的数据进行form校验</span></span><br><span class="line">        <span class="comment"># 调用form_obj校验数据的方法</span></span><br><span class="line">        <span class="keyword">if</span> form_obj.is_valid():</span><br><span class="line">            <span class="keyword">return</span> HttpResponse(<span class="string">"注册成功"</span>)</span><br><span class="line">    <span class="keyword">return</span> render(request, <span class="string">"register2.html"</span>, &#123;<span class="string">"form_obj"</span>: form_obj&#125;)</span><br></pre></td></tr></table></figure>

<p>2、login2.html</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">    &lt;title&gt;注册2&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;form action=<span class="string">"/reg2/"</span> method=<span class="string">"post"</span> novalidate autocomplete=<span class="string">"off"</span>&gt;  <span class="comment">#novalidate 告诉前端form表单，不要对输入的内容做校验</span></span><br><span class="line">        &#123;% csrf_token %&#125;</span><br><span class="line">        <span class="comment">#&#123;&#123; form_obj.as_p &#125;&#125;  直接写个这个，下面的用户名和密码的标签不自己写，你看看效果</span></span><br><span class="line">        &lt;div&gt;</span><br><span class="line">            &lt;label for="&#123;&#123; form_obj.name.id_for_label &#125;&#125;"&gt;&#123;&#123; form_obj.name.label &#125;&#125;&lt;/label&gt;</span><br><span class="line">            &#123;&#123; form_obj.name &#125;&#125; &#123;&#123; form_obj.name.errors<span class="number">.0</span> &#125;&#125;  <span class="comment">#errors是这个字段所有的错误，我就用其中一个错误提示就可以了，再错了再提示，并且不是给你生成ul标签了，单纯的是错误文本</span></span><br><span class="line">           &#123;&#123; form_obj.errors &#125;&#125; <span class="comment">#这是全局的所有错误，找对应字段的错误，就要form_obj.字段名</span></span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">        &lt;div&gt;</span><br><span class="line">            &lt;label for="&#123;&#123; form_obj.pwd.id_for_label &#125;&#125;"&gt;&#123;&#123; form_obj.pwd.label &#125;&#125;&lt;/label&gt;</span><br><span class="line">            &#123;&#123; form_obj.pwd &#125;&#125; &#123;&#123; form_obj.pwd.errors<span class="number">.0</span> &#125;&#125;</span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">        &lt;div&gt;</span><br><span class="line">            &lt;input type="submit" class="btn btn-success" value="注册"&gt;</span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">    &lt;/form&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>

<p>看网页效果发现 也验证了form的功能：<br>　　　前端页面是form类的对象生成的                                      –&gt;生成HTML标签功能<br>　　　当用户名和密码输入为空或输错之后 页面都会提示        –&gt;用户提交校验功能<br>　　　当用户输错之后 再次输入 上次的内容还保留在input框   –&gt;保留上次输入内容</p>
<h3 id="二、-Form常用字段与插件"><a href="#二、-Form常用字段与插件" class="headerlink" title="二、 Form常用字段与插件"></a>二、 Form常用字段与插件</h3><p>　　创建Form类时，主要涉及到 【字段】 和 【插件】，字段用于对用户请求数据的验证，插件用于自动生成HTML;</p>
<h3 id="3-1initial"><a href="#3-1initial" class="headerlink" title="3.1initial"></a>3.1initial</h3><p>初始值，input框里面的初始值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginForm</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    username = forms.CharField(  </span><br><span class="line">        min_length=<span class="number">8</span>,</span><br><span class="line">        label=<span class="string">"用户名"</span>,</span><br><span class="line">        initial=<span class="string">"张三"</span>  <span class="comment"># 设置默认值</span></span><br><span class="line">    )</span><br><span class="line">    pwd = forms.CharField(min_length=<span class="number">6</span>, label=<span class="string">"密码"</span>)</span><br></pre></td></tr></table></figure>

<h3 id="3-2error-messages"><a href="#3-2error-messages" class="headerlink" title="3.2error_messages"></a>3.2error_messages</h3><p>重写错误信息。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginForm</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    username = forms.CharField(</span><br><span class="line">        min_length=<span class="number">8</span>,</span><br><span class="line">        label=<span class="string">"用户名"</span>,</span><br><span class="line">        initial=<span class="string">"张三"</span>,</span><br><span class="line">        error_messages=&#123;</span><br><span class="line">            <span class="string">"required"</span>: <span class="string">"不能为空"</span>,</span><br><span class="line">            <span class="string">"invalid"</span>: <span class="string">"格式错误"</span>,</span><br><span class="line">            <span class="string">"min_length"</span>: <span class="string">"用户名最短8位"</span></span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line">    pwd = forms.CharField(min_length=<span class="number">6</span>, label=<span class="string">"密码"</span>)</span><br></pre></td></tr></table></figure>

<h3 id="3-3password"><a href="#3-3password" class="headerlink" title="3.3password"></a>3.3password</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginForm</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    ...</span><br><span class="line">    pwd = forms.CharField(</span><br><span class="line">        min_length=<span class="number">6</span>,</span><br><span class="line">        label=<span class="string">"密码"</span>,</span><br><span class="line">        widget=forms.widgets.PasswordInput(attrs=&#123;<span class="string">'class'</span>: <span class="string">'c1'</span>&#125;, render_value=<span class="literal">True</span>) </span><br><span class="line">        <span class="comment">#这个密码字段和其他字段不一样，默认在前端输入数据错误的时候，点击提交之后，默认是不保存的原来数据的，但是可以通过这个render_value=True让这个字段在前端保留用户输入的数据</span></span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

<h3 id="3-4radioSelect"><a href="#3-4radioSelect" class="headerlink" title="3.4radioSelect"></a>3.4radioSelect</h3><p>单radio值为字符串</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginForm</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    username = forms.CharField(  <span class="comment">#其他选择框或者输入框，基本都是在这个CharField的基础上通过插件来搞的</span></span><br><span class="line">        min_length=<span class="number">8</span>,</span><br><span class="line">        label=<span class="string">"用户名"</span>,</span><br><span class="line">        initial=<span class="string">"张三"</span>,</span><br><span class="line">        error_messages=&#123;</span><br><span class="line">            <span class="string">"required"</span>: <span class="string">"不能为空"</span>,</span><br><span class="line">            <span class="string">"invalid"</span>: <span class="string">"格式错误"</span>,</span><br><span class="line">            <span class="string">"min_length"</span>: <span class="string">"用户名最短8位"</span></span><br><span class="line">        &#125;</span><br><span class="line">    )</span><br><span class="line">    pwd = forms.CharField(min_length=<span class="number">6</span>, label=<span class="string">"密码"</span>)</span><br><span class="line">    gender = forms.fields.ChoiceField(</span><br><span class="line">        choices=((<span class="number">1</span>, <span class="string">"男"</span>), (<span class="number">2</span>, <span class="string">"女"</span>), (<span class="number">3</span>, <span class="string">"保密"</span>)),</span><br><span class="line">        label=<span class="string">"性别"</span>,</span><br><span class="line">        initial=<span class="number">3</span>,</span><br><span class="line">        widget=forms.widgets.RadioSelect()</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

<h3 id="3-5单选Select"><a href="#3-5单选Select" class="headerlink" title="3.5单选Select"></a>3.5单选Select</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginForm</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    ...</span><br><span class="line">    hobby = forms.fields.ChoiceField(</span><br><span class="line">        choices=((<span class="number">1</span>, <span class="string">"篮球"</span>), (<span class="number">2</span>, <span class="string">"足球"</span>), (<span class="number">3</span>, <span class="string">"双色球"</span>), ),</span><br><span class="line">        label=<span class="string">"爱好"</span>,</span><br><span class="line">        initial=<span class="number">3</span>,</span><br><span class="line">        widget=forms.widgets.Select()</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

<h3 id="3-6多选Select"><a href="#3-6多选Select" class="headerlink" title="3.6多选Select"></a>3.6多选Select</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginForm</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    ...</span><br><span class="line">    hobby = forms.fields.MultipleChoiceField(</span><br><span class="line">        choices=((<span class="number">1</span>, <span class="string">"篮球"</span>), (<span class="number">2</span>, <span class="string">"足球"</span>), (<span class="number">3</span>, <span class="string">"双色球"</span>), ),</span><br><span class="line">        label=<span class="string">"爱好"</span>,</span><br><span class="line">        initial=[<span class="number">1</span>, <span class="number">3</span>],</span><br><span class="line">        widget=forms.widgets.SelectMultiple()</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

<h3 id="3-7单选checkbox"><a href="#3-7单选checkbox" class="headerlink" title="3.7单选checkbox"></a>3.7单选checkbox</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginForm</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    ...</span><br><span class="line">    keep = forms.fields.ChoiceField(</span><br><span class="line">        label=<span class="string">"是否记住密码"</span>,</span><br><span class="line">        initial=<span class="string">"checked"</span>,</span><br><span class="line">        widget=forms.widgets.CheckboxInput()</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

<h3 id="3-8多选checkbox"><a href="#3-8多选checkbox" class="headerlink" title="3.8多选checkbox"></a>3.8多选checkbox</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginForm</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    ...</span><br><span class="line">    hobby = forms.fields.MultipleChoiceField(</span><br><span class="line">        choices=((<span class="number">1</span>, <span class="string">"篮球"</span>), (<span class="number">2</span>, <span class="string">"足球"</span>), (<span class="number">3</span>, <span class="string">"双色球"</span>),),</span><br><span class="line">        label=<span class="string">"爱好"</span>,</span><br><span class="line">        initial=[<span class="number">1</span>, <span class="number">3</span>],</span><br><span class="line">        widget=forms.widgets.CheckboxSelectMultiple()</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

<h3 id="3-9choice字段注意事项"><a href="#3-9choice字段注意事项" class="headerlink" title="3.9choice字段注意事项"></a>3.9choice字段注意事项</h3><p>　　　在使用选择标签时，需要注意choices的选项可以配置从数据库中获取，但是由于是静态字段 获取的值无法实时更新，需要重写构造方法从而实现choice实时更新。</p>
<p>方式一：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.forms <span class="keyword">import</span> Form</span><br><span class="line"><span class="keyword">from</span> django.forms <span class="keyword">import</span> widgets</span><br><span class="line"><span class="keyword">from</span> django.forms <span class="keyword">import</span> fields</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyForm</span><span class="params">(Form)</span>:</span></span><br><span class="line"> </span><br><span class="line">    user = fields.ChoiceField(</span><br><span class="line">        <span class="comment"># choices=((1, '上海'), (2, '北京'),),</span></span><br><span class="line">        initial=<span class="number">2</span>,</span><br><span class="line">        widget=widgets.Select</span><br><span class="line">    )</span><br><span class="line"> </span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, *args, **kwargs)</span>:</span></span><br><span class="line">        super(MyForm,self).__init__(*args, **kwargs)</span><br><span class="line">        <span class="comment"># self.fields['user'].choices = ((1, '上海'), (2, '北京'),)</span></span><br><span class="line">        <span class="comment"># 或</span></span><br><span class="line">        self.fields[<span class="string">'user'</span>].choices = models.Classes.objects.all().values_list(<span class="string">'id'</span>,<span class="string">'caption'</span>)</span><br></pre></td></tr></table></figure>

<p>方式二：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django <span class="keyword">import</span> forms</span><br><span class="line"><span class="keyword">from</span> django.forms <span class="keyword">import</span> fields</span><br><span class="line"><span class="keyword">from</span> django.forms <span class="keyword">import</span> models <span class="keyword">as</span> form_model</span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FInfo</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all())  <span class="comment"># 多选</span></span><br><span class="line">    <span class="comment"># authors = form_model.ModelChoiceField(queryset=models.NNewType.objects.all())  # 单选</span></span><br></pre></td></tr></table></figure>

<h2 id="三-Form所有内置字段"><a href="#三-Form所有内置字段" class="headerlink" title="三 Form所有内置字段"></a>三 Form所有内置字段</h2><p>见附录一</p>
<h2 id="四-字段校验"><a href="#四-字段校验" class="headerlink" title="四 字段校验"></a>四 字段校验</h2><h3 id="4-1RegexValidator验证器"><a href="#4-1RegexValidator验证器" class="headerlink" title="4.1RegexValidator验证器"></a>4.1RegexValidator验证器</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">from django.forms import Form</span><br><span class="line">from django.forms import widgets</span><br><span class="line">from django.forms import fields</span><br><span class="line">from django.core.validators import RegexValidator</span><br><span class="line"> </span><br><span class="line">class MyForm(Form):</span><br><span class="line">    user = fields.CharField(</span><br><span class="line">        validators=[RegexValidator(r&apos;^[0-9]+$&apos;, &apos;请输入数字&apos;), RegexValidator(r&apos;^159[0-9]+$&apos;, &apos;数字必须以159开头&apos;)],</span><br><span class="line">    )</span><br></pre></td></tr></table></figure>

<h3 id="4-2自定义验证函数"><a href="#4-2自定义验证函数" class="headerlink" title="4.2自定义验证函数"></a>4.2自定义验证函数</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> re</span><br><span class="line"><span class="keyword">from</span> django.forms <span class="keyword">import</span> Form</span><br><span class="line"><span class="keyword">from</span> django.forms <span class="keyword">import</span> widgets</span><br><span class="line"><span class="keyword">from</span> django.forms <span class="keyword">import</span> fields</span><br><span class="line"><span class="keyword">from</span> django.core.exceptions <span class="keyword">import</span> ValidationError</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"><span class="comment"># 自定义验证规则</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">mobile_validate</span><span class="params">(value)</span>:</span></span><br><span class="line">    mobile_re = re.compile(<span class="string">r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]&#123;8&#125;$'</span>)</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> mobile_re.match(value):</span><br><span class="line">        <span class="keyword">raise</span> ValidationError(<span class="string">'手机号码格式错误'</span>)  </span><br><span class="line">        <span class="comment">#自定义验证规则的时候，如果不符合你的规则，需要自己发起错误</span></span><br><span class="line"></span><br><span class="line"> </span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PublishForm</span><span class="params">(Form)</span>:</span></span><br><span class="line">    title = fields.CharField(max_length=<span class="number">20</span>,</span><br><span class="line">                            min_length=<span class="number">5</span>,</span><br><span class="line">                            error_messages=&#123;<span class="string">'required'</span>: <span class="string">'标题不能为空'</span>,</span><br><span class="line">                                            <span class="string">'min_length'</span>: <span class="string">'标题最少为5个字符'</span>,</span><br><span class="line">                                            <span class="string">'max_length'</span>: <span class="string">'标题最多为20个字符'</span>&#125;,</span><br><span class="line">                            widget=widgets.TextInput(attrs=&#123;<span class="string">'class'</span>: <span class="string">"form-control"</span>,</span><br><span class="line">                                                          <span class="string">'placeholder'</span>: <span class="string">'标题5-20个字符'</span>&#125;))</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">    <span class="comment"># 使用自定义验证规则</span></span><br><span class="line">    phone = fields.CharField(validators=[mobile_validate, ],</span><br><span class="line">                            error_messages=&#123;<span class="string">'required'</span>: <span class="string">'手机不能为空'</span>&#125;,</span><br><span class="line">                            widget=widgets.TextInput(attrs=&#123;<span class="string">'class'</span>: <span class="string">"form-control"</span>,</span><br><span class="line">                                                          <span class="string">'placeholder'</span>: <span class="string">u'手机号码'</span>&#125;))</span><br><span class="line"> </span><br><span class="line">    email = fields.EmailField(required=<span class="literal">False</span>,</span><br><span class="line">                            error_messages=&#123;<span class="string">'required'</span>: <span class="string">u'邮箱不能为空'</span>,<span class="string">'invalid'</span>: <span class="string">u'邮箱格式错误'</span>&#125;,</span><br><span class="line">                            widget=widgets.TextInput(attrs=&#123;<span class="string">'class'</span>: <span class="string">"form-control"</span>, <span class="string">'placeholder'</span>: <span class="string">u'邮箱'</span>&#125;))</span><br></pre></td></tr></table></figure>

<h2 id="五-Hook钩子方法"><a href="#五-Hook钩子方法" class="headerlink" title="五 Hook钩子方法"></a>五 Hook钩子方法</h2><p>　　除了上面两种方式，我们还可以在Form类中定义钩子函数，来实现自定义的验证功能。</p>
<h3 id="5-1局部钩子"><a href="#5-1局部钩子" class="headerlink" title="5.1局部钩子"></a>5.1局部钩子</h3><p>　　我们在Fom类中定义 clean_字段名() 方法，就能够实现对特定字段进行校验。</p>
<p>　　举个例子：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginForm</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    username = forms.CharField(</span><br><span class="line">        min_length=<span class="number">8</span>,</span><br><span class="line">        label=<span class="string">"用户名"</span>,</span><br><span class="line">        initial=<span class="string">"张三"</span>,</span><br><span class="line">        error_messages=&#123;</span><br><span class="line">            <span class="string">"required"</span>: <span class="string">"不能为空"</span>,</span><br><span class="line">            <span class="string">"invalid"</span>: <span class="string">"格式错误"</span>,</span><br><span class="line">            <span class="string">"min_length"</span>: <span class="string">"用户名最短8位"</span></span><br><span class="line">        &#125;,</span><br><span class="line">        widget=forms.widgets.TextInput(attrs=&#123;<span class="string">"class"</span>: <span class="string">"form-control"</span>&#125;)</span><br><span class="line">    )</span><br><span class="line">    ...</span><br><span class="line">    <span class="comment"># 定义局部钩子，用来校验username字段,之前的校验股则还在，给你提供了一个添加一些校验功能的钩子</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">clean_username</span><span class="params">(self)</span>:</span></span><br><span class="line">        value = self.cleaned_data.get(<span class="string">"username"</span>)</span><br><span class="line">        <span class="keyword">if</span> <span class="string">"666"</span> <span class="keyword">in</span> value:</span><br><span class="line">            <span class="keyword">raise</span> ValidationError(<span class="string">"光喊666是不行的"</span>)</span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            <span class="keyword">return</span> value</span><br></pre></td></tr></table></figure>

<h3 id="5-2全局钩子"><a href="#5-2全局钩子" class="headerlink" title="5.2全局钩子"></a>5.2全局钩子</h3><p>　　　我们在Fom类中定义 clean() 方法，就能够实现对字段进行全局校验，字段全部验证完，局部钩子也全部执行完之后，执行这个全局钩子校验。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginForm</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    ...</span><br><span class="line">    password = forms.CharField(</span><br><span class="line">        min_length=<span class="number">6</span>,</span><br><span class="line">        label=<span class="string">"密码"</span>,</span><br><span class="line">        widget=forms.widgets.PasswordInput(attrs=&#123;<span class="string">'class'</span>: <span class="string">'form-control'</span>&#125;, render_value=<span class="literal">True</span>)</span><br><span class="line">    )</span><br><span class="line">    re_password = forms.CharField(</span><br><span class="line">        min_length=<span class="number">6</span>,</span><br><span class="line">        label=<span class="string">"确认密码"</span>,</span><br><span class="line">        widget=forms.widgets.PasswordInput(attrs=&#123;<span class="string">'class'</span>: <span class="string">'form-control'</span>&#125;, render_value=<span class="literal">True</span>)</span><br><span class="line">    )</span><br><span class="line">    ...</span><br><span class="line">    <span class="comment"># 定义全局的钩子，用来校验密码和确认密码字段是否相同，执行全局钩子的时候，cleaned_data里面肯定是有了通过前面验证的所有数据</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">clean</span><span class="params">(self)</span>:</span></span><br><span class="line">        password_value = self.cleaned_data.get(<span class="string">'password'</span>)</span><br><span class="line">        re_password_value = self.cleaned_data.get(<span class="string">'re_password'</span>)</span><br><span class="line">        <span class="keyword">if</span> password_value == re_password_value:</span><br><span class="line">            <span class="keyword">return</span> self.cleaned_data <span class="comment">#全局钩子要返回所有的数据</span></span><br><span class="line">        <span class="keyword">else</span>:</span><br><span class="line">            self.add_error(<span class="string">'re_password'</span>, <span class="string">'两次密码不一致'</span>) <span class="comment">#在re_password这个字段的错误列表中加上一个错误，并且clean_data里面会自动清除这个re_password的值，所以打印clean_data的时候会看不到它</span></span><br><span class="line">            <span class="keyword">raise</span> ValidationError(<span class="string">'两次密码不一致'</span>)</span><br></pre></td></tr></table></figure>

<h2 id="六-、应用Bootstrap样式"><a href="#六-、应用Bootstrap样式" class="headerlink" title="六 、应用Bootstrap样式"></a>六 、应用Bootstrap样式</h2><h3 id="6-1简单实例"><a href="#6-1简单实例" class="headerlink" title="6.1简单实例"></a>6.1简单实例</h3><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">  &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">  &lt;meta http-equiv=<span class="string">"x-ua-compatible"</span> content=<span class="string">"IE=edge"</span>&gt;</span><br><span class="line">  &lt;meta name=<span class="string">"viewport"</span> content=<span class="string">"width=device-width, initial-scale=1"</span>&gt;</span><br><span class="line">  &lt;link rel=<span class="string">"stylesheet"</span> href=<span class="string">"/static/bootstrap/css/bootstrap.min.css"</span>&gt;</span><br><span class="line">  &lt;title&gt;login&lt;/title&gt;</span><br><span class="line">&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">&lt;div class="container"&gt;</span><br><span class="line">  &lt;div class="row"&gt;</span><br><span class="line">    &lt;form action="/login2/" method="post" novalidate class="form-horizontal"&gt;</span><br><span class="line">      &#123;% csrf_token %&#125;</span><br><span class="line">      &lt;div class="form-group"&gt;</span><br><span class="line">        &lt;label <span class="keyword">for</span>=<span class="string">"&#123;&#123; form_obj.username.id_for_label &#125;&#125;"</span></span><br><span class="line">               class="col-md-2 control-label"&gt;&#123;&#123; form_obj.username.label &#125;&#125;&lt;/label&gt;</span><br><span class="line">        &lt;div class="col-md-10"&gt;</span><br><span class="line">          &#123;&#123; form_obj.username &#125;&#125;</span><br><span class="line">          &lt;span class="help-block"&gt;&#123;&#123; form_obj.username.errors.0 &#125;&#125;&lt;/span&gt;</span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">      &lt;/div&gt;</span><br><span class="line">      &lt;div class="form-group"&gt;</span><br><span class="line">        &lt;label for="&#123;&#123; form_obj.pwd.id_for_label &#125;&#125;" class="col-md-2 control-label"&gt;&#123;&#123; form_obj.pwd.label &#125;&#125;&lt;/label&gt;</span><br><span class="line">        &lt;div class="col-md-10"&gt;</span><br><span class="line">          &#123;&#123; form_obj.pwd &#125;&#125;</span><br><span class="line">          &lt;span class="help-block"&gt;&#123;&#123; form_obj.pwd.errors.0 &#125;&#125;&lt;/span&gt;</span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">      &lt;/div&gt;</span><br><span class="line">      &lt;div class="form-group"&gt;</span><br><span class="line">      &lt;label class="col-md-2 control-label"&gt;&#123;&#123; form_obj.gender.label &#125;&#125;&lt;/label&gt;</span><br><span class="line">        &lt;div class="col-md-10"&gt;</span><br><span class="line">          &lt;div class="radio"&gt;</span><br><span class="line">            &#123;% <span class="keyword">for</span> radio <span class="keyword">in</span> form_obj.gender %&#125;</span><br><span class="line">              &lt;label <span class="keyword">for</span>=<span class="string">"&#123;&#123; radio.id_for_label &#125;&#125;"</span>&gt;</span><br><span class="line">                &#123;&#123; radio.tag &#125;&#125;&#123;&#123; radio.choice_label &#125;&#125;</span><br><span class="line">              &lt;/label&gt;</span><br><span class="line">            &#123;% endfor %&#125;</span><br><span class="line">          &lt;/div&gt;</span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">      &lt;/div&gt;</span><br><span class="line">      &lt;div class="form-group"&gt;</span><br><span class="line">        &lt;div class="col-md-offset-2 col-md-10"&gt;</span><br><span class="line">          &lt;button type="submit" class="btn btn-default"&gt;注册&lt;/button&gt;</span><br><span class="line">        &lt;/div&gt;</span><br><span class="line">      &lt;/div&gt;</span><br><span class="line">    &lt;/form&gt;</span><br><span class="line">  &lt;/div&gt;</span><br><span class="line">&lt;/div&gt;</span><br><span class="line"></span><br><span class="line">&lt;script src="/static/jquery-3.2.1.min.js"&gt;&lt;/script&gt;</span><br><span class="line">&lt;script src="/static/bootstrap/js/bootstrap.min.js"&gt;&lt;/script&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>

<h3 id="6-2批量添加样式"><a href="#6-2批量添加样式" class="headerlink" title="6.2批量添加样式"></a>6.2批量添加样式</h3><p>可通过重写form类的init方法来实现。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoginForm</span><span class="params">(forms.Form)</span>:</span></span><br><span class="line">    username = forms.CharField(</span><br><span class="line">        min_length=<span class="number">8</span>,</span><br><span class="line">        label=<span class="string">"用户名"</span>,</span><br><span class="line">        initial=<span class="string">"张三"</span>,</span><br><span class="line">        error_messages=&#123;</span><br><span class="line">            <span class="string">"required"</span>: <span class="string">"不能为空"</span>,</span><br><span class="line">            <span class="string">"invalid"</span>: <span class="string">"格式错误"</span>,</span><br><span class="line">            <span class="string">"min_length"</span>: <span class="string">"用户名最短8位"</span></span><br><span class="line">        &#125;</span><br><span class="line">    ...</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, *args, **kwargs)</span>:</span></span><br><span class="line">        super(LoginForm, self).__init__(*args, **kwargs)</span><br><span class="line">        <span class="keyword">for</span> field <span class="keyword">in</span> iter(self.fields):</span><br><span class="line">            self.fields[field].widget.attrs.update(&#123;</span><br><span class="line">                <span class="string">'class'</span>: <span class="string">'form-control'</span></span><br><span class="line">            &#125;)</span><br></pre></td></tr></table></figure>

<h2 id="七-ModelForm"><a href="#七-ModelForm" class="headerlink" title="七 ModelForm"></a>七 ModelForm</h2><p>　　通常在Django项目中，我们编写的大部分都是与Django 的模型紧密映射的表单。 举个例子，你也许会有个Book 模型，并且你还想创建一个form表单用来添加和编辑书籍信息到这个模型中。 在这种情况下，在form表单中定义字段将是冗余的，因为我们已经在模型中定义了那些字段。</p>
<p>　　基于这个原因，Django 提供一个辅助类来让我们可以从Django 的模型创建Form，这就是ModelForm。</p>
<h3 id="7-1modelForm定义"><a href="#7-1modelForm定义" class="headerlink" title="7.1modelForm定义"></a>7.1modelForm定义</h3><p>1、form与model的终极结合。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BookForm</span><span class="params">(forms.ModelForm)</span>:</span></span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Meta</span>:</span></span><br><span class="line">        model = models.Book</span><br><span class="line">        fields = <span class="string">"__all__"</span></span><br><span class="line">        labels = &#123;</span><br><span class="line">            <span class="string">"title"</span>: <span class="string">"书名"</span>,</span><br><span class="line">            <span class="string">"price"</span>: <span class="string">"价格"</span></span><br><span class="line">        &#125;</span><br><span class="line">        widgets = &#123;</span><br><span class="line">            <span class="string">"password"</span>: forms.widgets.PasswordInput(attrs=&#123;<span class="string">"class"</span>: <span class="string">"c1"</span>&#125;),</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>

<h3 id="7-2class-Meta下常用参数："><a href="#7-2class-Meta下常用参数：" class="headerlink" title="7.2class Meta下常用参数："></a>7.2class Meta下常用参数：</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">model = models.Book  <span class="comment"># 对应的Model中的类</span></span><br><span class="line">fields = <span class="string">"__all__"</span>  <span class="comment"># 字段，如果是__all__,就是表示列出所有的字段</span></span><br><span class="line">exclude = <span class="literal">None</span>  <span class="comment"># 排除的字段</span></span><br><span class="line">labels = <span class="literal">None</span>  <span class="comment"># 提示信息</span></span><br><span class="line">help_texts = <span class="literal">None</span>  <span class="comment"># 帮助提示信息</span></span><br><span class="line">widgets = <span class="literal">None</span>  <span class="comment"># 自定义插件</span></span><br><span class="line">error_messages = <span class="literal">None</span>  <span class="comment"># 自定义错误信息</span></span><br></pre></td></tr></table></figure>

<h3 id="7-3ModelForm的验证"><a href="#7-3ModelForm的验证" class="headerlink" title="7.3ModelForm的验证"></a>7.3ModelForm的验证</h3><p>　　　　与普通的Form表单验证类型类似，ModelForm表单的验证在调用is_valid() 或访问errors 属性时隐式调用。</p>
<p>　　　　我们可以像使用Form类一样自定义局部钩子方法和全局钩子方法来实现自定义的校验规则。</p>
<p>　　　　如果我们不重写具体字段并设置validators属性的化，ModelForm是按照模型中字段的validators来校验的。</p>
<h3 id="7-4save-方法"><a href="#7-4save-方法" class="headerlink" title="7.4save()方法"></a>7.4save()方法</h3><p>　　　每个ModelForm还具有一个save()方法。 这个方法根据表单绑定的数据创建并保存数据库对象。 ModelForm的子类可以接受现有的模型实例作为关键字参数instance；如果提供此功能，则save()将更新该实例。 如果没有提供，save() 将创建模型的一个新实例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> myapp.models <span class="keyword">import</span> Book</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> myapp.forms <span class="keyword">import</span> BookForm</span><br><span class="line"></span><br><span class="line"><span class="comment"># 根据POST数据创建一个新的form对象</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>form_obj = BookForm(request.POST)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 创建书籍对象</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>new_ book = form_obj.save()</span><br><span class="line"></span><br><span class="line"><span class="comment"># 基于一个书籍对象创建form对象</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>edit_obj = Book.objects.get(id=<span class="number">1</span>)</span><br><span class="line"><span class="comment"># 使用POST提交的数据更新书籍对象</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>form_obj = BookForm(request.POST, instance=edit_obj)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>form_obj.save()</span><br></pre></td></tr></table></figure>

<h2 id="八-附录"><a href="#八-附录" class="headerlink" title="八 附录"></a>八 附录</h2><h3 id="8-1附录一（内置字段）"><a href="#8-1附录一（内置字段）" class="headerlink" title="8.1附录一（内置字段）"></a>8.1附录一（内置字段）</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br></pre></td><td class="code"><pre><span class="line">Field</span><br><span class="line">    required=<span class="literal">True</span>,               是否允许为空</span><br><span class="line">    widget=<span class="literal">None</span>,                 HTML插件</span><br><span class="line">    label=<span class="literal">None</span>,                  用于生成Label标签或显示内容</span><br><span class="line">    initial=<span class="literal">None</span>,                初始值</span><br><span class="line">    help_text=<span class="string">''</span>,                帮助信息(在标签旁边显示)</span><br><span class="line">    error_messages=<span class="literal">None</span>,         错误信息 &#123;<span class="string">'required'</span>: <span class="string">'不能为空'</span>, <span class="string">'invalid'</span>: <span class="string">'格式错误'</span>&#125;</span><br><span class="line">    validators=[],               自定义验证规则</span><br><span class="line">    localize=<span class="literal">False</span>,              是否支持本地化</span><br><span class="line">    disabled=<span class="literal">False</span>,              是否可以编辑</span><br><span class="line">    label_suffix=<span class="literal">None</span>            Label内容后缀</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">CharField(Field)</span><br><span class="line">    max_length=<span class="literal">None</span>,             最大长度</span><br><span class="line">    min_length=<span class="literal">None</span>,             最小长度</span><br><span class="line">    strip=<span class="literal">True</span>                   是否移除用户输入空白</span><br><span class="line"> </span><br><span class="line">IntegerField(Field)</span><br><span class="line">    max_value=<span class="literal">None</span>,              最大值</span><br><span class="line">    min_value=<span class="literal">None</span>,              最小值</span><br><span class="line"> </span><br><span class="line">FloatField(IntegerField)</span><br><span class="line">    ...</span><br><span class="line"> </span><br><span class="line">DecimalField(IntegerField)</span><br><span class="line">    max_value=<span class="literal">None</span>,              最大值</span><br><span class="line">    min_value=<span class="literal">None</span>,              最小值</span><br><span class="line">    max_digits=<span class="literal">None</span>,             总长度</span><br><span class="line">    decimal_places=<span class="literal">None</span>,         小数位长度</span><br><span class="line"> </span><br><span class="line">BaseTemporalField(Field)</span><br><span class="line">    input_formats=<span class="literal">None</span>          时间格式化   </span><br><span class="line"> </span><br><span class="line">DateField(BaseTemporalField)    格式：<span class="number">2015</span><span class="number">-09</span><span class="number">-01</span></span><br><span class="line">TimeField(BaseTemporalField)    格式：<span class="number">11</span>:<span class="number">12</span></span><br><span class="line">DateTimeField(BaseTemporalField)格式：<span class="number">2015</span><span class="number">-09</span><span class="number">-01</span> <span class="number">11</span>:<span class="number">12</span></span><br><span class="line"> </span><br><span class="line">DurationField(Field)            时间间隔：%d %H:%M:%S.%f</span><br><span class="line">    ...</span><br><span class="line"> </span><br><span class="line">RegexField(CharField)</span><br><span class="line">    regex,                      自定制正则表达式</span><br><span class="line">    max_length=<span class="literal">None</span>,            最大长度</span><br><span class="line">    min_length=<span class="literal">None</span>,            最小长度</span><br><span class="line">    error_message=<span class="literal">None</span>,         忽略，错误信息使用 error_messages=&#123;<span class="string">'invalid'</span>: <span class="string">'...'</span>&#125;</span><br><span class="line"> </span><br><span class="line">EmailField(CharField)      </span><br><span class="line">    ...</span><br><span class="line"> </span><br><span class="line">FileField(Field)</span><br><span class="line">    allow_empty_file=<span class="literal">False</span>     是否允许空文件</span><br><span class="line"> </span><br><span class="line">ImageField(FileField)      </span><br><span class="line">    ...</span><br><span class="line">    注：需要PIL模块，pip3 install Pillow</span><br><span class="line">    以上两个字典使用时，需要注意两点：</span><br><span class="line">        - form表单中 enctype=<span class="string">"multipart/form-data"</span></span><br><span class="line">        - view函数中 obj = MyForm(request.POST, request.FILES)</span><br><span class="line"> </span><br><span class="line">URLField(Field)</span><br><span class="line">    ...</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">BooleanField(Field)  </span><br><span class="line">    ...</span><br><span class="line"> </span><br><span class="line">NullBooleanField(BooleanField)</span><br><span class="line">    ...</span><br><span class="line"> </span><br><span class="line">ChoiceField(Field)</span><br><span class="line">    ...</span><br><span class="line">    choices=(),                选项，如：choices = ((<span class="number">0</span>,<span class="string">'上海'</span>),(<span class="number">1</span>,<span class="string">'北京'</span>),)</span><br><span class="line">    required=<span class="literal">True</span>,             是否必填</span><br><span class="line">    widget=<span class="literal">None</span>,               插件，默认select插件</span><br><span class="line">    label=<span class="literal">None</span>,                Label内容</span><br><span class="line">    initial=<span class="literal">None</span>,              初始值</span><br><span class="line">    help_text=<span class="string">''</span>,              帮助提示</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">ModelChoiceField(ChoiceField)</span><br><span class="line">    ...                        django.forms.models.ModelChoiceField</span><br><span class="line">    queryset,                  <span class="comment"># 查询数据库中的数据</span></span><br><span class="line">    empty_label=<span class="string">"---------"</span>,   <span class="comment"># 默认空显示内容</span></span><br><span class="line">    to_field_name=<span class="literal">None</span>,        <span class="comment"># HTML中value的值对应的字段</span></span><br><span class="line">    limit_choices_to=<span class="literal">None</span>      <span class="comment"># ModelForm中对queryset二次筛选</span></span><br><span class="line">     </span><br><span class="line">ModelMultipleChoiceField(ModelChoiceField)</span><br><span class="line">    ...                        django.forms.models.ModelMultipleChoiceField</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line">     </span><br><span class="line">TypedChoiceField(ChoiceField)</span><br><span class="line">    coerce = <span class="keyword">lambda</span> val: val   对选中的值进行一次转换</span><br><span class="line">    empty_value= <span class="string">''</span>            空值的默认值</span><br><span class="line"> </span><br><span class="line">MultipleChoiceField(ChoiceField)</span><br><span class="line">    ...</span><br><span class="line"> </span><br><span class="line">TypedMultipleChoiceField(MultipleChoiceField)</span><br><span class="line">    coerce = <span class="keyword">lambda</span> val: val   对选中的每一个值进行一次转换</span><br><span class="line">    empty_value= <span class="string">''</span>            空值的默认值</span><br><span class="line"> </span><br><span class="line">ComboField(Field)</span><br><span class="line">    fields=()                  使用多个验证，如下：即验证最大长度<span class="number">20</span>，又验证邮箱格式</span><br><span class="line">                               fields.ComboField(fields=[fields.CharField(max_length=<span class="number">20</span>), fields.EmailField(),])</span><br><span class="line"> </span><br><span class="line">MultiValueField(Field)</span><br><span class="line">    PS: 抽象类，子类中可以实现聚合多个字典去匹配一个值，要配合MultiWidget使用</span><br><span class="line"> </span><br><span class="line">SplitDateTimeField(MultiValueField)</span><br><span class="line">    input_date_formats=<span class="literal">None</span>,   格式列表：[<span class="string">'%Y--%m--%d'</span>, <span class="string">'%m%d/%Y'</span>, <span class="string">'%m/%d/%y'</span>]</span><br><span class="line">    input_time_formats=<span class="literal">None</span>    格式列表：[<span class="string">'%H:%M:%S'</span>, <span class="string">'%H:%M:%S.%f'</span>, <span class="string">'%H:%M'</span>]</span><br><span class="line"> </span><br><span class="line">FilePathField(ChoiceField)     文件选项，目录下文件显示在页面中</span><br><span class="line">    path,                      文件夹路径</span><br><span class="line">    match=<span class="literal">None</span>,                正则匹配</span><br><span class="line">    recursive=<span class="literal">False</span>,           递归下面的文件夹</span><br><span class="line">    allow_files=<span class="literal">True</span>,          允许文件</span><br><span class="line">    allow_folders=<span class="literal">False</span>,       允许文件夹</span><br><span class="line">    required=<span class="literal">True</span>,</span><br><span class="line">    widget=<span class="literal">None</span>,</span><br><span class="line">    label=<span class="literal">None</span>,</span><br><span class="line">    initial=<span class="literal">None</span>,</span><br><span class="line">    help_text=<span class="string">''</span></span><br><span class="line"> </span><br><span class="line">GenericIPAddressField</span><br><span class="line">    protocol=<span class="string">'both'</span>,           both,ipv4,ipv6支持的IP格式</span><br><span class="line">    unpack_ipv4=<span class="literal">False</span>          解析ipv4地址，如果是::ffff:<span class="number">192.0</span><span class="number">.2</span><span class="number">.1</span>时候，可解析为<span class="number">192.0</span><span class="number">.2</span><span class="number">.1</span>， PS：protocol必须为both才能启用</span><br><span class="line"> </span><br><span class="line">SlugField(CharField)           数字，字母，下划线，减号（连字符）</span><br><span class="line">    ...</span><br><span class="line"> </span><br><span class="line">UUIDField(CharField)           uuid类型</span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://yoursite.com/2019/09/21/【Django】09From表单和ModelForm组件/" title="Form和ModelForm">http://yoursite.com/2019/09/21/【Django】09From表单和ModelForm组件/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/dxl/tags/Django/" rel="tag"># Django</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/dxl/2019/09/21/【内容回顾】03-2django - 副本/" rel="next" title="Django">
                <i class="fa fa-chevron-left"></i> Django
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/dxl/2019/09/21/【Django】02路由系统/" rel="prev" title="路由系统">
                路由系统 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/dxl/images/avatar.png" alt>
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/dxl/archives">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/dxl/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/dxl/tags/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-sign-out"></i>
                我的友链
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="tencent://message/?Menu=yes&uin=1258517737&Site=QQ%E6%9E%81%E5%AE%A2&Service=300&sigT=45a1e5847943b64c6ff3990f8a9e644d2b31356cb0b4ac6b24663a3c8dd0f8aa12a595b1714f9d45/" title="申请坑位" target="_blank">申请坑位</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#一-Form介绍"><span class="nav-number">1.</span> <span class="nav-text">一 Form介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1Form组件的主要功能如下"><span class="nav-number">1.1.</span> <span class="nav-text">2.1Form组件的主要功能如下:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2普通方式手写注册功能"><span class="nav-number">1.2.</span> <span class="nav-text">2.2普通方式手写注册功能</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2使用form组件实现注册功能"><span class="nav-number">1.3.</span> <span class="nav-text">2.2使用form组件实现注册功能</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、-Form常用字段与插件"><span class="nav-number">1.4.</span> <span class="nav-text">二、 Form常用字段与插件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1initial"><span class="nav-number">1.5.</span> <span class="nav-text">3.1initial</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2error-messages"><span class="nav-number">1.6.</span> <span class="nav-text">3.2error_messages</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3password"><span class="nav-number">1.7.</span> <span class="nav-text">3.3password</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4radioSelect"><span class="nav-number">1.8.</span> <span class="nav-text">3.4radioSelect</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-5单选Select"><span class="nav-number">1.9.</span> <span class="nav-text">3.5单选Select</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-6多选Select"><span class="nav-number">1.10.</span> <span class="nav-text">3.6多选Select</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-7单选checkbox"><span class="nav-number">1.11.</span> <span class="nav-text">3.7单选checkbox</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-8多选checkbox"><span class="nav-number">1.12.</span> <span class="nav-text">3.8多选checkbox</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-9choice字段注意事项"><span class="nav-number">1.13.</span> <span class="nav-text">3.9choice字段注意事项</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#三-Form所有内置字段"><span class="nav-number">2.</span> <span class="nav-text">三 Form所有内置字段</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#四-字段校验"><span class="nav-number">3.</span> <span class="nav-text">四 字段校验</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-1RegexValidator验证器"><span class="nav-number">3.1.</span> <span class="nav-text">4.1RegexValidator验证器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2自定义验证函数"><span class="nav-number">3.2.</span> <span class="nav-text">4.2自定义验证函数</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#五-Hook钩子方法"><span class="nav-number">4.</span> <span class="nav-text">五 Hook钩子方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1局部钩子"><span class="nav-number">4.1.</span> <span class="nav-text">5.1局部钩子</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-2全局钩子"><span class="nav-number">4.2.</span> <span class="nav-text">5.2全局钩子</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#六-、应用Bootstrap样式"><span class="nav-number">5.</span> <span class="nav-text">六 、应用Bootstrap样式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#6-1简单实例"><span class="nav-number">5.1.</span> <span class="nav-text">6.1简单实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-2批量添加样式"><span class="nav-number">5.2.</span> <span class="nav-text">6.2批量添加样式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#七-ModelForm"><span class="nav-number">6.</span> <span class="nav-text">七 ModelForm</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#7-1modelForm定义"><span class="nav-number">6.1.</span> <span class="nav-text">7.1modelForm定义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-2class-Meta下常用参数："><span class="nav-number">6.2.</span> <span class="nav-text">7.2class Meta下常用参数：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-3ModelForm的验证"><span class="nav-number">6.3.</span> <span class="nav-text">7.3ModelForm的验证</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-4save-方法"><span class="nav-number">6.4.</span> <span class="nav-text">7.4save()方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#八-附录"><span class="nav-number">7.</span> <span class="nav-text">八 附录</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#8-1附录一（内置字段）"><span class="nav-number">7.1.</span> <span class="nav-text">8.1附录一（内置字段）</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-hand-peace-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder"></span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/dxl/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/dxl/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/dxl/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/dxl/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/dxl/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/dxl/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/dxl/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/dxl/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/dxl/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '13B0JGDuA6ttduN8AQaR8CzF-gzGzoHsz',
        appKey: 'I13r9r5mVgq4jQYpYy6V4gW3',
        placeholder: '欢迎大佬指点~~~',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  





  

  

  

  
  

  

  

  

</body>
</html>
